/*
 * SocketUDP.hpp
 *
 *  Created on: 11.04.2011
 *      Author: mifodix
 */

#ifndef SOCKETUDP_HPP_
#define SOCKETUDP_HPP_

#ifndef __cplusplus
#error Need C++-compile to process this file
#endif

#include <stdio.h>
#include <string.h>
#include "Logger.hpp"

#if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64)
	#include "winsock2.h"
	#pragma comment (lib, "ws2_32.lib")
	#include <stdint.h>
	#include "Ws2tcpip.h"
	#define CLOSE_SOCKET(x) closesocket(x)
	#define SOCK_OPTION_TYPE char
	#define FINISH() WSACleanup();
	#define INITIALIZE() WSADATA wsaData; \
									int iResult = WSAStartup( MAKEWORD(2,2), &wsaData ); \

#endif

#if  defined(linux) || defined(__linux) || defined(unix) || defined(__unix)
	#include <sys/socket.h>
	#include <netinet/in.h>
	#include <sys/types.h>
	#include <arpa/inet.h>
	#include <unistd.h>
	#define INVALID_SOCKET -1
	#define SOCKET_ERROR -1
	#define CLOSE_SOCKET(x) close(x)
	#define SOCKET int
	#define SOCK_OPTION_TYPE int
	#define INITIALIZE()
	#define FINISH()
#endif
/*
 *
 */
class SocketUDP
{
private:
	SOCKET mySocket;
	sockaddr_in myAddress;
	bool isBroadcast;
	bool isBounded;
public:
	SocketUDP(): isBounded(false)
	{
		INITIALIZE();
	}
	bool Bind(const char* bindAddress="0.0.0.0", uint16_t port=67, bool isBroadcast=false);
	bool Bind(uint32_t bindAddress=0, uint16_t port=67, bool isBroadcast=false);//ПРЯМОЙ ПОРЯДОК!
	int ReceiveAll(void* packet, size_t packetSize, char* fromAddress, uint16_t &port);
	int Receive(void *packet, size_t packetSize, char *fromAddress, uint16_t &port);
	int SendAll(void* packet, size_t packetSize, const char* toAddress, uint16_t port=68);
	virtual ~SocketUDP();
};

#endif /* SOCKETUDP_HPP_ */
